package com.ycproxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLDecoder;

public class YcClassLoader extends ClassLoader {

    private final File classPathFile;

    public YcClassLoader() {
        String classPath = YcClassLoader.class.getResource("").getPath();
        this.classPathFile = new File(classPath);
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = YcClassLoader.class.getPackage().getName() + "." + name + ".class";
        if (classPathFile != null) {
            String path = null;
            try {
                path = URLDecoder.decode(classPathFile.getPath(), "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            File classFile = new File(path, name.replace("\\.", "/") + ".class");
            if (classFile.exists()) {
                try (
                        FileInputStream in = new FileInputStream(classFile);
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                ) {
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = in.read(buff)) != -1) {
                        out.write(buff, 0, len);
                    }
                    out.flush();
                    System.out.println(out.toByteArray().toString());
                    System.out.println("++++++++++");
                    System.out.println(className);
                    return defineClass("ycproxy." + name, out.toByteArray(), 0, out.size());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static boolean registerAsParallelCapable() {
        return ClassLoader.registerAsParallelCapable();
    }


    private byte[] loadClassData() {
//        try (
//                FileInputStream stream = new FileInputStream(file);
//        ) {
//            return stream.readAllBytes();
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        return null;
    }

}
